<script setup>
import { ref } from "vue";
import Topbar from "@/components/Topbar/index.vue";
import getRules from "@/validUtils";
import UploadImg from "@/components/UploadImg/index.vue";
import {
  uniqueFunc,
  buildTrees,
  limitFloat,
  giveFloatMin,
  giveIntMin,
  limitInt,
  getFieldValue,
} from "@/utils/common.js";
import { getDistInfo } from "@/api/Other";
import TabelBrand from "@/components/TableComponents/Brand.vue";
import {
  getBaseSetting,
  getAllCommodityExtraAttributes,
} from "@/api/ShopDatabase/goodsSetting.js";
import {
  getPageProjects,
  getPageProducts,
  getDiagnosis,
  saveCourse,
  selectCourseDetail,
} from "@/api/EngageManagement/cureManagement.js";
import { pinyin } from "pinyin-pro";
import { useRoute } from "vue-router";
import useDiffValue from "@/views/EngageManagement/ShopDatabase/ProductManagement/Hooks/useDiffValue.js";

const route = useRoute();
const backValue = ref("CureManagementIndex");
const tabName = ref("编辑疗程");
const businessBrandOptions = ref([]);
const formRef = ref();
const loading = ref(false);
const form = reactive({
  code: " ",
  courseName: "",
  mnemonicCode: "",
  businessBrandId: [],
  pictureList: [],
  times: "",
  validity: "",
  diagnosisList: [],
  salesState: 1,
  retailPrice: "",
  costPrice: "",
  minSellingPrice: "", //最低售价
});

const suitOptions = ref([]);
const uuid = computed(() => {
  return route.query.id;
});
const backValueActivityImg = (img) => {
  form.pictureList = img;
  formRef.value.clearValidate(["pictureList"]);
};
const projectData = ref([]);
const reduceArry = () => {
  projectData.value = [
    ...selectCheckData.value,
    ...selectCheckDataProject.value,
  ];
};
//  -----------------产品
const formInline = ref([
  {
    type: "datePicker",
    prop: ["startDate", "endDate"],
    startPlaceholder: "创建开始时间",
    endPlaceholder: "创建结束时间",
    label: "",
    model: [],
  },
  {
    type: "input",
    prop: "fuzzyValue",
    placeholder: "产品名称/编号",
    label: "",
    model: "",
  },
  {
    type: "select",
    placeholder: "产品类别",
    label: "",
    filterable: true,
    prop: "categoryId",
    data: [],
    model: "",
  },
  {
    type: "select",
    placeholder: "经营品牌",
    filterable: true,
    label: "",
    prop: "businessBrandId",
    data: [],
    loading: false,
    multiple: true,
    disabled: true,
    model: "",
  },
]);
const tableConfig = ref([
  {
    prop: "code",
    label: "产品编号",
    type: "slot",
    slotName: "code",
    width: 150,
  },
  {
    prop: "productName",
    label: "产品名称",
    type: "slot",
    slotName: "productName",
    width: 220,
    textOverflow: true,
  },
  {
    prop: "category",
    label: "产品类别",
    width: 100,
  },
  {
    prop: "businessBrandId",
    label: "经营品牌",
    width: 100,
    type: "slot",
    slotName: "businessBrandId",
    textOverflow: true,
  },
  {
    prop: "specification",
    label: "产品规格",
    width: 100,
  },
  {
    prop: "unit",
    label: "单位",
    width: 100,
  },
  {
    prop: "salesState",
    label: "销售状态",
    width: 100,
    type: "slot",
    slotName: "salesState",
  },
  {
    prop: "createTime",
    label: "创建时间",
    width: 250,
  },
]);
const tableLoading = ref(false);
const totalPage = ref(0);
const tableData = ref([]);
const productFlag = ref(false);
const selectCheckData = ref([]);
const seachTable = ref(null);
const handlerSearch = async (formInline) => {
  const businessBrandId = form.businessBrandId.join(",");
  if (!formInline.businessBrandId?.length) {
    formInline.businessBrandId = businessBrandId;
  } else {
    formInline.businessBrandId = formInline.businessBrandId.join(",");
  }
  tableLoading.value = true;
  try {
    const { records, total } = await getPageProducts(formInline);
    totalPage.value = total;
    tableData.value = records;
    tableLoading.value = false;
  } catch (e) {
    tableLoading.value = false;
  } finally {
    nextTick(() => {
      toggleSelection();
    });
  }
};
const selectHandle = (val, row) => {
  let index = selectCheckData.value.map((value) => value.id).indexOf(row.id);
  if (index >= 0) {
    removeData([row.id]);
  } else {
    selectCheckData.value = uniqueFunc([row, ...selectCheckData.value], "id");
  }
};
const selectAllChange = (col) => {
  if (col.length > 0) {
    selectCheckData.value = uniqueFunc(
      [...col, ...selectCheckData.value],
      "id"
    );
  } else {
    let ids = tableData.value.map((value) => value.id);
    removeData(ids);
  }
};
//移除未选中的数据
const removeData = (uuids) => {
  selectCheckData.value = selectCheckData.value.filter(
    (value) => !uuids.includes(value.id)
  );
};
const toggleSelection = () => {
  //获取所有选中的uuid
  let ids = selectCheckData.value.map((value) => value.id);
  //过滤获取相同值
  let repeatValue = tableData.value.filter((value) => ids.includes(value.id));
  seachTable.value.checkHaveData(repeatValue);
};

//  ----------------项目
const formInlineProject = ref([
  {
    type: "datePicker",
    prop: ["startDate", "endDate"],
    startPlaceholder: "创建开始时间",
    endPlaceholder: "创建结束时间",
    label: "",
    model: [],
  },
  {
    type: "input",
    prop: "fuzzyValue",
    placeholder: "项目名称/编号",
    label: "",
    model: "",
  },
  {
    type: "select",
    placeholder: "销售分类",
    filterable: true,
    label: "",
    prop: "salesClassIdList",
    data: [],
    multiple: true,
    model: [],
  },
  {
    type: "select",
    placeholder: "经营品牌",
    filterable: true,
    label: "",
    prop: "businessBrandId",
    data: [],
    model: "",
    multiple: true,
    disabled: true,
    loading: false,
  },
]);
const tableConfigProject = ref([
  {
    prop: "code",
    label: "项目编号",
    type: "slot",
    slotName: "code",
    width: 140,
  },
  {
    prop: "projectName",
    label: "项目名称",
    type: "slot",
    slotName: "projectName",
    width: 220,
    textOverflow: true,
  },
  {
    prop: "businessBrandId",
    label: "经营品牌",
    type: "slot",
    slotName: "businessBrandId",
    width: 140,
    textOverflow: true,
  },
  {
    prop: "salesClass",
    label: "销售分类",
    width: 100,
    textOverflow: true,
  },
  {
    prop: "existsDisposables",
    label: "关联耗材",
    width: 100,
    type: "slot",
    slotName: "existsDisposables",
  },
  {
    prop: "salesState",
    label: "销售状态",
    width: 100,
    type: "slot",
    slotName: "salesState",
  },
  {
    prop: "createTime",
    label: "创建时间",
    width: 250,
  },
]);
const tableLoadingProject = ref(false);
const totalPageProject = ref(0);
const tableDataProject = ref([]);
const ProjectFlag = ref(false);
const selectCheckDataProject = ref([]);
const seachTableProject = ref(null);
const confrimProjectState = ref(false);
const confrimProductState = ref(false);
const handlerSearchProject = async (formInline) => {
  const businessBrandId = form.businessBrandId.join(",");
  if (!formInline.businessBrandId?.length) {
    formInline.businessBrandId = businessBrandId;
  } else {
    formInline.businessBrandId = formInline.businessBrandId.join(",");
  }
  tableLoadingProject.value = true;
  try {
    const { records, total } = await getPageProjects(formInline);
    totalPageProject.value = total;
    tableDataProject.value = records;
    tableLoadingProject.value = false;
  } catch (e) {
    tableLoadingProject.value = false;
  } finally {
    nextTick(() => {
      toggleSelectionProject();
    });
  }
};
const selectHandleProject = (val, row) => {
  let index = selectCheckDataProject.value
    .map((value) => value.id)
    .indexOf(row.id);
  if (index >= 0) {
    removeDataProject([row.id]);
  } else {
    selectCheckDataProject.value = uniqueFunc(
      [row, ...selectCheckDataProject.value],
      "id"
    );
  }
};
const selectAllChangeProject = (col) => {
  if (col.length > 0) {
    selectCheckDataProject.value = uniqueFunc(
      [...col, ...selectCheckDataProject.value],
      "id"
    );
  } else {
    let ids = tableDataProject.value.map((value) => value.id);
    removeDataProject(ids);
  }
};
//移除未选中的数据
const removeDataProject = (uuids) => {
  selectCheckDataProject.value = selectCheckDataProject.value.filter(
    (value) => uuids.indexOf(value.id) == -1
  );
};
const toggleSelectionProject = () => {
  //获取所有选中的uuid
  let ids = selectCheckDataProject.value.map((value) => value.id);
  //过滤获取相同值
  let repeatValue = tableDataProject.value.filter((value) =>
    ids.includes(value.id)
  );
  seachTableProject.value.checkHaveData(repeatValue);
};

// -----------弹窗
const openProductList = async () => {
  formInline.value[formInline.value.length - 1].data =
    businessBrandOptions.value.filter((v) =>
      form.businessBrandId.includes(v.value)
    );
  formInline.value[formInline.value.length - 1].model = form.businessBrandId;
  productFlag.value = true;
  selectCheckData.value = projectData.value.filter((v) => v["category"]);
  selectCheckDataProject.value = projectData.value.filter(
    (v) => !v["category"]
  );
};
const openProjectList = async () => {
  formInlineProject.value[formInlineProject.value.length - 1].data =
    businessBrandOptions.value.filter((v) =>
      form.businessBrandId.includes(v.value)
    );
  formInlineProject.value[formInlineProject.value.length - 1].model =
    form.businessBrandId;
  ProjectFlag.value = true;
  // 添加项目
  selectCheckDataProject.value = projectData.value.filter(
    (v) => !v["category"]
  );
  selectCheckData.value = projectData.value.filter((v) => v["category"]);
};
const confrimProduct = () => {
  confrimProductState.value = true;
  selectCheckData.value = selectCheckData.value.map((v) => ({
    ...v,
    times: v.times || "",
    unitPrice: v.unitPrice || v.retailPrice,
  }));
  productFlag.value = false;
  if (selectCheckData.value.length > 50) {
    ElMessage.warning("最多只能选择50个产品");
    return;
  }
  reduceArry();
};

const closeProduct = ()=>{
  productFlag.value = false
  confrimProductState.value = false
}

const closeDialogProduct = ()=>{
  if(!confrimProductState.value){
    selectCheckData.value = []
  }
}

const confrimProject = () => {
  confrimProjectState.value = true
  selectCheckDataProject.value = selectCheckDataProject.value.map((v) => ({
    ...v,
    unitPrice: v.unitPrice || v.retailPrice,
  }));
  ProjectFlag.value = false;
  if (selectCheckDataProject.value.length > 50) {
    ElMessage.warning("最多只能选择50个项目");
    return;
  }
  reduceArry();
};


const closeProject = () => {
  ProjectFlag.value = false;
  confrimProjectState.value = false
  
}
const closeDialogProject = ()=>{
  if(!confrimProjectState.value){
    selectCheckDataProject.value = []
  }
}

const topBarRef = ref();
const closeBack = () => {
  topBarRef.value.backHandle();
};

const projectDataDel = (index) => {
  const item = projectData.value[index];
  projectData.value.splice(index, 1);
  if (selectCheckData.value.some((v) => v.id == item.id)) {
    const index = selectCheckData.value.findIndex((v) => v.id == item.id);
    selectCheckData.value.splice(index, 1);
  }
  if (selectCheckDataProject.value.some((v) => v.id == item.id)) {
    const index = selectCheckDataProject.value.findIndex(
      (v) => v.id == item.id
    );
    selectCheckDataProject.value.splice(index, 1);
  }
  if (!projectData.value.length) {
    form.retailPrice = "";
  }
};
const changeTimes = (row, key) => {
  if (key == "times") {
    row.times = limitInt(row.times);
  }
  if (key == "retailPrice") {
    row.retailPrice = limitFloat(row.retailPrice);
  }
  changeRetailPrice("", true);
};
const changeRetailPrice = (_value, state = false) => {
  if (!state) {
    form.retailPrice = limitFloat(form.retailPrice);
  }
  projectData.value.forEach((e) => {
    e.valueAmount =
      (Number(e.times) * Number(e.unitPrice)) % 1 != 0
        ? (Number(e.times) * Number(e.unitPrice)).toFixed(2)
        : Number(e.times) * Number(e.unitPrice);
    e.retailAmount =
      (Number(e.times) * Number(e.retailPrice)) % 1 != 0
        ? (Number(e.times) * Number(e.retailPrice)).toFixed(2)
        : Number(e.times) * Number(e.retailPrice);
  });
};

const blurRetailPrice = () => {
  form.retailPrice = giveFloatMin(form.retailPrice);
  nextTick(() => {
    changeRetailPrice("", true);
  });
  if (form.minSellingPrice) {
    formRef.value.validateField(["minSellingPrice"]);
  }
};

const blurTimes = (row) => {
  row.times = giveIntMin(row.times);
};

const orignSuitOptions = ref([]);
const courseAttributesList = ref([]);
// 品牌
const getBrandList = (res) => {
  formInline.value[formInline.value.length - 1]["loading"] = true;
  formInline.value[formInline.value.length - 1]["data"] = res;
  formInline.value[formInline.value.length - 1]["loading"] = false;
  formInlineProject.value[formInlineProject.value.length - 1]["loading"] = true;
  formInlineProject.value[formInlineProject.value.length - 1]["data"] = res;
  formInlineProject.value[formInlineProject.value.length - 1][
    "loading"
  ] = false;
};
const diagnosisRes = ref([]);
onActivated(async () => {
  loading.value = true;

  const res = await getAllCommodityExtraAttributes();
  courseAttributesList.value = res.courseAttributesList
    .filter((v) => !v.disabled)
    .map((v) => ({
      ...v,
      extraAttributesValue: "",
      optionContent: v.optionContent
        .split(",")
        .map((el) => ({ value: el, label: el })),
    }));
  const brandRes = await getDistInfo({ permissionType: 3 });
  businessBrandOptions.value = brandRes[0].groupData.map((v) => ({
    label: v.permissionName,
    value: v.id,
  }));
  getBrandList(businessBrandOptions.value);
  const baseResult = await getBaseSetting();
  formInlineProject.value[2].data = getFieldValue("销售分类", baseResult, "id");
  formInline.value[2].data = getFieldValue("类别", baseResult, "id");

  diagnosisRes.value = await getDiagnosis();
  await getDetail();
  businessBrandChange();
  loading.value = false;
});

const businessBrandChange = () => {
  orignSuitOptions.value = diagnosisRes.value.filter((v) =>
    v.permissionId?.split(",").some((el) => form.businessBrandId.includes(el))
  );
  suitOptions.value = buildTrees(
    orignSuitOptions.value.map((v) => ({
      value: v.id,
      id: v.id,
      parentId: v.parentId,
      label: v.diagnosisValue,
    }))
  );
  suitOptions.value.forEach((e) => {
    if (!e.children?.length) {
      e.disabled = true;
    }
  });
};

const saveLoading = ref(false);
// --------------保存
let oldDetails = {};
const sumbit = async () => {
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      const sourceType = 7;
      const diagnoMap = Array.from(new Set(form.diagnosisList.flat(Infinity)));

      const newValue = {
        retailPrice: +form.retailPrice,
        salesStatus: +form.salesState,
      };
      const isDiff = await useDiffValue(oldDetails, newValue);
      if (!isDiff) return;
      const diagnosisList = orignSuitOptions.value
        .filter((v) => diagnoMap.includes(v.id))
        .map((el) => ({
          sourceType: sourceType,
          diagnosisId: el.id,
          diagnosisValue: el.diagnosisValue,
        }));
      const project = projectData.value
        .filter((v) => !v["category"])
        .map((v) => ({
          baseId: v.id,
          sourceType: 2,
          times: void 0,
          unitPrice: v.unitPrice,
          valueAmount: void 0,
          retailPrice: "", //v.retailPrice,
          retailAmount: void 0,
          commodityName: v.projectName,
          commodityPicture: v.firstPicture,
          commodityCode: v.code,
        }));
      const product = projectData.value
        .filter((v) => v["category"])
        .map((v) => ({
          baseId: v.id,
          sourceType: 1,
          times: Number(v.times),
          unitPrice: v.unitPrice,
          valueAmount: v.valueAmount,
          retailPrice: v.retailPrice,
          retailAmount: v.retailAmount,
          commodityName: v.productName,
          commodityPicture: v.firstPicture,
          commodityCode: v.code,
        }));
      const contentlList = [...project, ...product];
      const pictureList = form.pictureList.map((v) => ({
        url: v,
        sourceType: sourceType,
      }));

      const attributeList = courseAttributesList.value.map((v) => ({
        extraAttributesId: v.id,
        sourceType: sourceType,
        extraAttributesName: v.fieldName,
        fieldType: v.fieldType,
        optionContent: v.optionContent.map((el) => el.value).join(","),
        extraAttributesValue: Array.isArray(v.extraAttributesValue)
          ? v.extraAttributesValue.join(",")
          : v.extraAttributesValue,
      }));
      const obj = {
        add: 0,
        code: form.code.trim(),
        id: uuid.value,
        courseName: form.courseName,
        mnemonicCode: form.mnemonicCode,
        businessBrandId: form.businessBrandId.join(","),
        salesState: form.salesState,
        retailPrice: Number(form.retailPrice),
        costPrice: form.costPrice && Number(form.costPrice),
        minSellingPrice: Number(form.minSellingPrice), //最低售价
        validity: Number(form.validity),
        times: Number(form.times),
        diagnosisList: diagnosisList,
        contentlList: contentlList,
        pictureList: pictureList,
        attributeList: attributeList,
      };
      saveLoading.value = true;
      await saveCourse(obj);
      saveLoading.value = false;
      sessionStorage.setItem("closeTagName", "CureManagementEdit");
      closeBack();
    } else {
      ElMessage.error("基础信息未填写完整");
      console.log("error submit!", fields);
    }
  });
};

const getDetail = async () => {
  projectData.value = [];
  const res = await selectCourseDetail(uuid.value);
  oldDetails = {
    retailPrice: +res.retailPrice,
    salesStatus: +res.salesState,
  };
  form.code = res.code;
  form.courseName = res.courseName;
  form.mnemonicCode = res.mnemonicCode;
  form.businessBrandId = res.businessBrandId.split(",");
  form.pictureList = res.pictureList.map((v) => v.url);
  form.times = res.times;
  form.validity = res.validity;
  form.diagnosisList = res.diagnosisList.map((v) => v.diagnosisId);
  form.salesState = res.salesState;
  form.retailPrice = res.retailPrice;
  form.costPrice = res.costPrice;
  form.minSellingPrice = res.minSellingPrice; //最低售价
  const project = res.projectList.map((v) => ({
    ...v,
    id: v.baseId,
    sourceType: v.sourceType,
    times: void 0,
    unitPrice: v.unitPrice,
    valueAmount: void 0,
    retailPrice: v.retailPrice,
    retailAmount: void 0,
    projectName: v.commodityName,
    firstPicture: v.commodityPicture,
    code: v.commodityCode,
  }));
  const product = res.productList.map((v) => ({
    ...v,
    id: v.baseId,
    sourceType: v.sourceType,
    times: Number(v.times),
    unitPrice: v.unitPrice,
    valueAmount: v.valueAmount,
    retailPrice: v.retailPrice,
    retailAmount: v.retailAmount,
    productName: v.commodityName,
    firstPicture: v.commodityPicture,
    code: v.commodityCode,
    category: "产品",
  }));

  projectData.value = [...product, ...project];
  courseAttributesList.value.forEach((e) => {
    res.attributeList.forEach((el) => {
      if (el.extraAttributesId == e.id) {
        if (e.fieldType == 4) {
          e.extraAttributesValue =
            el.extraAttributesValue && el.extraAttributesValue.split(",");
        } else {
          e.extraAttributesValue = el.extraAttributesValue;
        }
      }
    });
  });
  selectCheckDataProject.value = project;
  selectCheckData.value = product;
};
const nameInput = (val) => {
  const reg = /[\u4e00-\u9fa5]/g;
  const py = val.replace(reg, (match) => {
    return pinyin(match, {
      toneType: "none", // 设置拼音风格
      separator: "",
      pattern: "first",
    }).toLocaleUpperCase();
  });
  form.mnemonicCode = py;
};
const frequencyRules = (index) => {
  return [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (projectData.value[index].times) {
          callback();
        } else {
          callback(new Error("请输入次数/数量"));
        }
      },
      trigger: "blur",
    },
  ];
};
const retailPriceRules = [
  {
    required: true,
    validator: (rule, value, callback) => {
      if (value) {
        const list = projectData.value.filter((s) => Number(s.retailAmount));
        const numx =
          list
            .map((v) => v.retailAmount)
            .reduce((a, b) => Number(a) + Number(b), 0) || 0;
        if (Number(numx) > Number(form.retailPrice)) {
          callback(new Error("疗程零售价不能低于疗程中产品的零售金额之和"));
        } else {
          callback();
        }
      } else {
        callback(new Error("请输入零售价"));
      }
    },
    trigger: "blur",
  },
];

// 最低售价校验规则
const lowestPriceRules = [
  {
    required: true,
    validator: (rule, value, callback) => {
      console.log(value, "value");
      if (value) {
        const list = projectData.value.filter((s) => s.retailAmount);
        const numx =
          (list?.length &&
            list.map((v) => v.retailAmount).reduce((a, b) => a + b)) ||
          0;
        console.log(numx, "numx");
        if (
          value < 0.01 ||
          Number(form.minSellingPrice) > Number(form.retailPrice)
        ) {
          callback(
            new Error("最低售价需大于等于产品零售金额之和，小于等于零售价")
          );
        } else if (Number(numx) > Number(form.minSellingPrice)) {
          // form.retailPrice = Number(numx);
          callback(
            new Error("最低售价需大于等于产品零售金额之和，小于等于零售价")
          );
        } else {
          callback();
        }
      } else {
        callback(new Error("请输入最低售价"));
      }
    },
    trigger: "blur",
  },
];
</script>
<template>
  <div class="page-contain" v-loading="loading">
    <Topbar ref="topBarRef" :backValue="backValue" :tabName="tabName">
      <template #operate>
        <el-button style="min-width: 68px" @click="closeBack">取消</el-button>
        <el-button
          type="primary"
          style="min-width: 68px"
          @click="sumbit"
          :loading="saveLoading"
          >保存</el-button
        >
      </template>
    </Topbar>
    <div class="info-contain">
      <div class="info-lis">
        <el-form ref="formRef" :model="form" label-width="93px">
          <div class="lis-head">
            <div class="icon-view">
              <div class="icon-view-on"></div>
            </div>
            <span class="label-name">基础属性</span>
          </div>
          <div class="lis-item">
            <div class="lis-i">
              <el-form-item
                label="疗程编号"
                prop="code"
                :label-width="'auto'"
                :rules="[{ required: true }]"
              >
                <el-input
                  v-model="form.code"
                  placeholder="保存后自动生成"
                  disabled
                  style="width: 260px"
                />
              </el-form-item>
            </div>
            <div class="lis-i">
              <el-form-item
                label="疗程名称"
                :rules="getRules('input', '疗程名称')"
                prop="courseName"
              >
                <el-input
                  v-model="form.courseName"
                  placeholder="请输入"
                  :maxlength="50"
                  show-word-limit
                  @input="nameInput"
                  style="width: 260px"
                />
              </el-form-item>
            </div>
            <div class="lis-i">
              <el-form-item
                label="助记码"
                prop="mnemonicCode"
                :rules="getRules('input', '助记码')"
              >
                <el-input
                  v-model="form.mnemonicCode"
                  placeholder="请输入"
                  style="width: 260px"
                />
              </el-form-item>
            </div>
          </div>
          <div class="lis-item">
            <div class="lis-i">
              <el-form-item
                label="经营品牌"
                :rules="getRules('select', '经营品牌')"
                prop="businessBrandId"
              >
                <el-select
                  v-model="form.businessBrandId"
                  placeholder="请选择"
                  clearable
                  multiple
                  collapse-tags
                  collapse-tags-tooltip
                  v-selectClose
                  style="width: 260px"
                  @change="businessBrandChange"
                >
                  <el-option
                    v-for="(item, index) in businessBrandOptions"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </div>
          </div>
          <div class="lis-item">
            <div class="lis-i" style="width: 100%">
              <el-form-item
                label="疗程图片"
                prop="pictureList"
                :rules="getRules('input', '疗程图片')"
              >
                <div style="width: 100%; position: relative">
                  <UploadImg
                    :multiple="true"
                    @backValue="backValueActivityImg"
                    :imageListUrlInfo="form.pictureList"
                  >
                  </UploadImg>
                  <div
                    style="
                      font-size: 12px;
                      color: #666666;
                      line-height: 12px;
                      width: 100%;
                      margin-top: 8px;
                    "
                  >
                    支持jpg、jpeg、png格式，图片比例1:1；建议为300*300，最多5张，单张不超过5M
                  </div>
                </div>
              </el-form-item>
            </div>
          </div>
          <div class="lis-item">
            <div class="lis-i" style="width: 100%">
              <el-form-item
                label="疗程内容"
                :rules="getRules('input', '疗程内容')"
              >
                <div style="width: 100%" v-if="form.businessBrandId?.length">
                  <el-button
                    plain
                    type="primary"
                    @click="openProjectList()"
                    :disabled="!form.businessBrandId?.length"
                  >
                    <img
                      src="@/assets/icon/btn-add-blue.png"
                      alt=""
                      style="margin-right: 8px; width: 14px; height: 14px"
                    />
                    添加项目
                  </el-button>
                  <el-button
                    plain
                    type="primary"
                    @click="openProductList()"
                    :disabled="!form.businessBrandId?.length"
                  >
                    <img
                      src="@/assets/icon/btn-add-blue.png"
                      alt=""
                      style="margin-right: 8px; width: 14px; height: 14px"
                    />
                    添加产品
                  </el-button>
                </div>
                <div v-else style="width: 100%">
                  <div class="noAddBtnClassBox">
                    <div class="noAddBtnClass">
                      <img
                        src="@/assets/icon/no-btn-add-blue.png"
                        alt=""
                        style="margin-right: 8px; width: 14px; height: 14px"
                      />
                      <div class="tips">添加项目</div>
                    </div>
                    <div class="noAddBtnClass">
                      <img
                        src="@/assets/icon/no-btn-add-blue.png"
                        alt=""
                        style="margin-right: 8px; width: 14px; height: 14px"
                      />
                      <div class="tips">添加产品</div>
                    </div>
                  </div>
                  <div class="noAddClass">
                    选择经营品牌后，才可添加项目/产品
                  </div>
                </div>
                <div
                  v-if="projectData.length"
                  style="width: 100%; margin-top: 8px"
                >
                  <el-table :data="projectData" style="width: 100%" stripe>
                    <el-table-column label="名称">
                      <template #="{ row }">
                        <el-tooltip
                          class="box-item"
                          effect="dark"
                          :content="row.projectName || row.productName"
                          placement="top"
                        >
                          <div class="content-view">
                            {{ row.projectName || row.productName }}
                          </div>
                        </el-tooltip>
                        <!-- {{ row.projectName || row.productName }} -->
                      </template>
                    </el-table-column>
                    <el-table-column label="类型">
                      <template #="{ row }">
                        {{ row["category"] ? "产品" : "项目" }}
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="date"
                      label="次数/数量"
                      min-width="100"
                    >
                      <template #="{ row, $index }">
                        <el-form-item
                          v-if="row['category']"
                          :prop="`projectData.value.${$index}.times`"
                          label=""
                          :inline-message="true"
                          :rules="row['category'] && frequencyRules($index)"
                        >
                          <el-input
                            v-if="row['category']"
                            v-model="row.times"
                            size="small"
                            style="width: 120px"
                            @input="changeTimes(row, 'times')"
                            @blur="blurTimes(row)"
                          />
                        </el-form-item>
                        <span v-else>-</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="unitPrice" label="单价">
                    </el-table-column>
                    <el-table-column label="价值金额">
                      <template #="{ row }">
                        <span v-if="row['category']">{{
                          row.valueAmount || 0
                        }}</span>
                        <span v-else>-</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="零售价">
                      <template #="{ row }">
                        <el-input
                          v-if="row['category']"
                          v-model="row.retailPrice"
                          size="small"
                          style="width: 120px"
                          @input="changeTimes(row, 'retailPrice')"
                          @blur="
                            () => {
                              row.retailPrice = giveFloatMin(row.retailPrice);
                            }
                          "
                        />
                        <span v-else>-</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="零售金额">
                      <template #="{ row }">
                        <span v-if="row['category']">
                          {{ row.retailAmount || 0 }}
                        </span>
                        <span v-else>-</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" fixed="right" width="120">
                      <template #default="{ row, $index }">
                        <el-button
                          type="danger"
                          plain
                          size="small"
                          @click="projectDataDel($index)"
                        >
                          删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-form-item>
            </div>
          </div>
          <div class="lis-item">
            <div class="lis-i" style="width: 100%">
              <el-form-item
                label="疗程次数"
                :rules="getRules('input', '疗程次数')"
                prop="times"
              >
                <el-input
                  v-model="form.times"
                  @input="
                    () => {
                      form.times = limitInt(form.times, 3);
                    }
                  "
                  @blur="
                    () => {
                      form.times = giveIntMin(form.times);
                    }
                  "
                  style="width: 120px"
                  placeholder="请输入"
                />
                <span
                  style="
                    line-height: 14px;
                    color: #000000;
                    font-size: 14px;
                    margin-left: 8px;
                  "
                  >次</span
                >
              </el-form-item>
            </div>
          </div>
          <div class="lis-item">
            <div class="lis-i" style="width: 100%">
              <el-form-item
                label="疗程有效期"
                :rules="getRules('input', '疗程有效期')"
                prop="validity"
              >
                <el-input
                  v-model="form.validity"
                  @input="
                    () => {
                      form.validity = limitInt(form.validity, 3);
                    }
                  "
                  @blur="
                    () => {
                      form.validity = giveIntMin(form.validity);
                    }
                  "
                  style="width: 120px"
                  placeholder="请输入"
                />
                <span
                  style="
                    line-height: 14px;
                    color: #000000;
                    font-size: 14px;
                    margin-left: 8px;
                  "
                  >天有效</span
                >
                <div
                  style="
                    font-size: 12px;
                    color: #666666;
                    line-height: 12px;
                    width: 100%;
                    margin-top: 8px;
                  "
                >
                  疗程的有效期将在用户核销项目的第一次生效
                </div>
              </el-form-item>
            </div>
          </div>
          <div class="lis-item">
            <div class="lis-i" style="width: 100%">
              <el-form-item
                label="适用诊断"
                prop="diagnosisList"
                :rules="getRules('select', '适用诊断')"
              >
                <el-cascader
                  v-model="form.diagnosisList"
                  style="width: 220px"
                  :options="suitOptions"
                  placeholder="请选择"
                  collapse-tags
                  collapse-tags-tooltip
                  :props="{ multiple: true }"
                >
                </el-cascader>
              </el-form-item>
            </div>
          </div>
          <div class="lis-item">
            <div class="lis-i" style="width: 100%">
              <el-form-item label="销售状态" prop="status">
                <el-radio-group v-model="form.salesState" class="ml-4">
                  <el-radio :label="1">正常</el-radio>
                  <el-radio :label="2">停售</el-radio>
                </el-radio-group>
                <div
                  style="
                    font-size: 12px;
                    color: #666666;
                    line-height: 12px;
                    width: 100%;
                    margin-top: 3px;
                  "
                >
                  设置针对经营该商品的所有门店生效
                </div>
              </el-form-item>
            </div>
          </div>
          <div class="lis-item">
            <div class="lis-i">
              <el-form-item
                label="零售价"
                :rules="retailPriceRules"
                prop="retailPrice"
              >
                <el-input
                  v-model="form.retailPrice"
                  placeholder="请输入"
                  style="width: 260px"
                  :disabled="!projectData.length"
                  @input="changeRetailPrice($event, false)"
                  @blur="blurRetailPrice"
                />
              </el-form-item>
            </div>
            <div class="lis-i">
              <el-form-item label="成本价" prop="costPrice">
                <el-input
                  v-model="form.costPrice"
                  placeholder="请输入"
                  style="width: 260px"
                  @input="
                    () => {
                      form.costPrice = limitFloat(form.costPrice);
                    }
                  "
                  @blur="
                    () => {
                      form.costPrice = giveFloatMin(form.costPrice);
                    }
                  "
                />
              </el-form-item>
            </div>
          </div>
          <div class="lis-item">
            <div class="lis-i">
              <el-form-item
                label="最低售价"
                prop="minSellingPrice"
                :rules="lowestPriceRules"
              >
                <el-input
                  style="width: 260px"
                  class="formWidth"
                  :maxlength="50"
                  @input="
                    () => {
                      form.minSellingPrice = limitFloat(form.minSellingPrice);
                    }
                  "
                  v-model.trim="form.minSellingPrice"
                  placeholder="请输入"
                ></el-input>
                <div
                  style="
                    font-size: 12px;
                    color: #666666;
                    line-height: 12px;
                    width: 100%;
                    margin-top: 10px;
                  "
                >
                  门店线上线下销售商品时，商品改价不得低于最低售价
                </div>
              </el-form-item>
            </div>
          </div>
          <div class="lis-head">
            <div class="icon-view">
              <div class="icon-view-on"></div>
            </div>
            <span class="label-name">自定义属性</span>
          </div>
          <div class="lis-item" style="flex-wrap: wrap">
            <div
              class="lis-i"
              v-for="(item, index) in courseAttributesList"
              :key="index"
            >
              <el-form-item :label="item.fieldName">
                <el-input
                  v-if="item.fieldType == 1"
                  v-model="item.extraAttributesValue"
                  placeholder="请输入"
                  style="width: 260px"
                />
                <el-input
                  v-if="item.fieldType == 2"
                  v-model="item.extraAttributesValue"
                  placeholder="请输入"
                  @input="
                    () => {
                      item.extraAttributesValue = limitFloat(
                        item.extraAttributesValue
                      );
                    }
                  "
                  style="width: 260px"
                />
                <el-select
                  v-if="item.fieldType == 3 || item.fieldType == 4"
                  v-model="item.extraAttributesValue"
                  placeholder="请选择"
                  clearable
                  v-selectClose
                  :multiple="item.fieldType == 4"
                  style="width: 260px"
                >
                  <el-option
                    v-for="(op, index) in item.optionContent"
                    :key="index"
                    :label="op.label"
                    :value="op.value"
                  />
                </el-select>
              </el-form-item>
            </div>
          </div>
        </el-form>
      </div>
    </div>
    <el-dialog
      :close-on-press-escape="false"
      destroy-on-close
      :close-on-click-modal="false"
      v-model="productFlag"
      title="选择产品"
      width="1000px"
      @close="closeDialogProduct"
    >
      <div style="width: 100%; height: 500px" v-if="productFlag">
        <SeachTable
          :tableType="1"
          ref="seachTable"
          :tableSelection="true"
          :forms="formInline"
          :tableLoading="tableLoading"
          :tableConfig="tableConfig"
          :tableData="tableData"
          :totalPage="totalPage"
          @handlerSearch="handlerSearch"
          @selectHandle="selectHandle"
          @selectAllHandle="selectAllChange"
          :showLine="false"
          :showBtn="false"
        >
          <template #code="{ row }">
            <div class="a-link">{{ row.code }}</div>
          </template>
          <template #productName="{ row }">
            <div class="project-info">
              <div class="img">
                <el-image
                  :src="row.firstPicture"
                  :zoom-rate="1.2"
                  :preview-src-list="[row.firstPicture]"
                  :initial-index="4"
                  preview-teleported
                  style="width: 100%; height: 100%"
                />
              </div>
              <div class="name-info">
                <div class="p1">{{ row.productName }}</div>
              </div>
            </div>
          </template>
          <template #existsDisposables="{ row }">
            {{ row.existsDisposables ? "是" : "否" }}
          </template>
          <template #salesState="{ row }">
            {{ row.salesState ? "正常" : "停售" }}
          </template>
          <template #businessBrandId="{ row }">
            <div v-if="row.businessBrandId && formInline[3].data?.length">
              <TabelBrand
                :id="item"
                :key="item"
                :index="index"
                :origin="row.businessBrandId.split(',')"
                v-for="(item, index) in row.businessBrandId.split(',')"
                :list="formInline[3].data"
              ></TabelBrand>
            </div>
            <div v-else>-</div>
          </template>
        </SeachTable>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeProduct">取消</el-button>
          <el-button type="primary" @click="confrimProduct()">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      :close-on-press-escape="false"
      destroy-on-close
      :close-on-click-modal="false"
      v-model="ProjectFlag"
      title="选择项目"
      width="1000px"
      @close="closeDialogProject"
    >
      <div style="width: 100%; height: 500px" v-if="ProjectFlag">
        <SeachTable
          :tableType="1"
          ref="seachTableProject"
          :tableSelection="true"
          :forms="formInlineProject"
          :tableLoading="tableLoadingProject"
          :tableConfig="tableConfigProject"
          :tableData="tableDataProject"
          :totalPage="totalPageProject"
          @handlerSearch="handlerSearchProject"
          @selectHandle="selectHandleProject"
          @selectAllHandle="selectAllChangeProject"
          :showLine="false"
          :showBtn="false"
        >
          <template #code="{ row }">
            <div class="a-link">{{ row.code }}</div>
          </template>
          <template #projectName="{ row }">
            <div class="project-info">
              <div class="img">
                <el-image
                  :src="row.firstPicture"
                  :zoom-rate="1.2"
                  :preview-src-list="[row.firstPicture]"
                  :initial-index="4"
                  preview-teleported
                  style="width: 100%; height: 100%"
                />
              </div>
              <div class="name-info">
                <div class="p1">{{ row.projectName }}</div>
              </div>
            </div>
          </template>
          <template #existsDisposables="{ row }">
            {{ row.existsDisposables ? "是" : "否" }}
          </template>
          <template #salesState="{ row }">
            {{ row.salesState ? "正常" : "停售" }}
          </template>
          <template #businessBrandId="{ row }">
            <div
              v-if="row.businessBrandId && formInlineProject[3].data?.length"
            >
              <TabelBrand
                :list="formInlineProject[3].data"
                :id="item"
                :key="item"
                :index="index"
                :origin="row.businessBrandId.split(',')"
                v-for="(item, index) in row.businessBrandId.split(',')"
              ></TabelBrand>
            </div>
            <div v-else>-</div>
          </template>
        </SeachTable>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeProject">取消</el-button>
          <el-button type="primary" @click="confrimProject()">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style lang="less" scoped>
:deep(.el-table__inner-wrapper::before) {
  display: none;
}
:deep(.el-table th.el-table__cell) {
  background: #ebebeb;
}
:deep(.el-dialog__body) {
  padding: 0 4px;
}
:deep(.el-table__header) {
  tr {
    th {
      &:last-child {
        .cell {
          border-right: 0px;
        }
      }
    }
  }
}
.page-contain {
  width: 100%;
  height: 100%;
  :deep(.el-table th > .cell) {
    border-right: 0;
  }
  :deep(.el-radio-button:first-child .el-radio-button__inner) {
    border-left: 1px solid #3480ff;
  }
  .info-contain {
    width: 100%;
    height: calc(100% - 48px);
    box-sizing: border-box;
    padding: 16px 24px 0;
    .btn-opea {
      width: 100%;
      height: 32px;
    }
    .info-lis {
      width: 100%;
      height: calc(100%);
      box-sizing: border-box;
      // padding-top:24px;
      overflow: auto;
      .lis-head {
        width: 100%;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        padding-bottom: 16px;
        .icon-view {
          margin-right: 8px;
          position: relative;
          width: 14px;
          height: 14px;

          &::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            width: 10px;
            height: 10px;
            border-radius: 2px;
            background-color: #10e7f9;
          }
          .icon-view-on {
            position: absolute;
            bottom: 0;
            right: 0;
            width: 10px;
            height: 10px;
            border-radius: 2px;
            background-color: #3480ff; /* 背景色 */
          }
        }
        .label-name {
          color: #000000;
          font-weight: bold;
          font-size: 14px;
          margin-right: 8px;
        }
        img {
          width: 14px;
          height: 14px;
          cursor: pointer;
        }
      }
    }
    .lis-item {
      width: 100%;
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      .lis-i {
        width: calc(100% / 3);
        margin-bottom: 10px;
        :deep(.el-form-item__label) {
          min-width: 96px;
        }
      }
    }
  }
  :deep(.el-table__row) {
    .el-input .el-input__wrapper {
      background: rgba(0, 0, 0, 0);
    }
  }
}
.input-line {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 16px;
  &:last-child {
    margin-bottom: 0px;
  }
  img {
    cursor: pointer;
    width: 16px;
    height: 16px;
    margin-left: 8px;
  }
}
.project-info {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;

  .img {
    width: 48px;
    height: 48px;
  }
  .name-info {
    width: calc(100% - 56px);
    box-sizing: border-box;
    padding-left: 8px;
    .p1 {
      width: 100%;
      color: #222222;
      font-weight: bold;
      line-height: 14px;
      font-size: 14px;
      height: 14px;
    }
    .p2 {
      width: 100%;
      margin-top: 8px;
      color: #666666;
      line-height: 14px;
      font-size: 14px;
      height: 14px;
    }
  }
}
.noAddBtnClassBox {
  display: flex;
  align-items: center;
  width: max-content;
  gap: 8px;
}
.noAddBtnClass {
  border-radius: 18px;
  background: #ddd;
  padding: 7px 16px;
  display: flex;
  align-items: center;
  line-height: normal;
  .tips {
    font-size: 14px;
    color: #666666;
    font-weight: 500;
    line-height: normal;
  }
}
.noAddClass {
  color: #666666;
  font-size: 12px;
  font-weight: 400;
  margin-top: 8px;
  line-height: normal;
}
.content-view {
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  width: 100%;
}
</style>
